<template>
  <div class="mod-prod">
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"

        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="formName"
            :label="$t('form.formName')+':'"
          >
            <el-input
              v-model="searchForm.formName"
              type="text"
              clearable
              :placeholder="$t('form.formName')"
            />
          </el-form-item>
          <el-form-item
            prop="timeType"
            :label="$t('form.reportType')+':'"
          >
            <el-select
              v-model="searchForm.timeType"
              clearable
              :placeholder="$t('form.reportType')"
            >
              <el-option
                v-for="item in reportType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetForm()"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('admin:form:save')"
          class="default-btn primary-btn"
          @click.stop="onAddOrUpdate()"
        >
          {{ $t("crud.addTitle") }}
        </div>
      </div>
      <div class="table-con form-table">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            align="left"
            prop="formName"
            :label="$t('form.formName')"
          />
          <el-table-column
            align="left"
            prop="updateTime"
            :label="$t('home.updateTime')"
          />
          <el-table-column
            align="left"
            :label="$t('form.reportType')"
          >
            <template #default="scope">
              <span>{{ ['',$t('form.day'),$t('form.week'),$t('form.month')][scope.row.timeType] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            width="220"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('admin:form:save')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.formId)"
                >
                  {{ $t('text.updateBtn') }}
                </div>
                <div
                  v-if="isAuth('admin:form:formExcel')"
                  class="default-btn text-btn"
                  @click="onGetFormExcel(scope.row)"
                >
                  {{ $t("formData.export") }}
                </div>
                <div
                  v-if="isAuth('admin:form:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.formId)"
                >
                  {{ $t('text.delBtn') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="onRefreshChange"
    />
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from '../components/add-or-update.vue'
import { isAuth } from '@/utils/index.js'

const reportType = [
  {
    label: $t('form.day'),
    value: 1
  }, {
    label: $t('form.week'),
    value: 2
  }, {
    label: $t('form.month'),
    value: 3
  }
]

onMounted(() => {
  onGetDataList(page)
})

// 获取数据列表
let tempSearchForm = null // 保存上次点击查询的请求条件
const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  timeType: null,
  formName: ''
})
const onGetDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/admin/form/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  })
}

// 新增 / 修改
const addOrUpdateRef = ref(null)
const addOrUpdateVisible = ref(false)
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id, false)
  })
}
// 删除
const onDelete = (id) => {
  ElMessageBox.confirm(`${$t('admin.isDeleOper')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/admin/form/' + id),
      method: 'delete'
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          onRefreshChange()
        }
      })
    })
  })
}
// 条件查询
const onSearch = (newData = false) => {
  onGetDataList(page, newData)
}
// 刷新回调
const onRefreshChange = () => {
  onGetDataList()
}
const onGetFormExcel = (form) => {
  http({
    url: http.adornUrl('/admin/form/formExcel'),
    method: 'get',
    params: http.adornParams({
      formId: form.formId
    }),
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = form.formName + '.xlsx'
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}
const onPageSizeChange = (val) => {
  page.pageSize = val
  onGetDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  onGetDataList()
}
const searchFormRef = ref(null)
const onResetForm = () => {
  searchFormRef.value.resetFields()
}
</script>
